package com.jd.myaaaccount;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.jd.myaaaccount.entity.DayBook;
import com.jd.myaaaccount.entity.Family;
import com.jd.myaaaccount.entity.Host;
import com.jd.myaaaccount.model.Common;
import com.jd.myaaaccount.model.DayBookModel;
import com.jd.myaaaccount.model.FamilyModel;
import com.jd.myaaaccount.util.AlertDialogHelper;
import com.jd.myaaaccount.util.ErrorCode;
import com.jd.myaaaccount.util.HttpHelper;
import com.jd.myaaaccount.util.OperateCode;

public class DayBookPage extends BasePage {
	private ListView lvDayBook;
	private ImageView ivFilter;
	private ImageView ivRefresh;
	private Handler handler;

	private FamilyModel fm;
	private DayBookModel dm;

	private int selectedFamilyIndex;
	private List<Family> families;
	private String[] familiesName;

	List<DayBook> daybooks = new ArrayList<DayBook>();
	DaybookAdapter dba = new DaybookAdapter();
	private Hashtable<String, Bitmap> cachImg = new Hashtable<String, Bitmap>();
	private Animation anim;

	@Override
	public void iniPage(Activity context) {
		super.iniPage(context);
		initControl();
		fm = new FamilyModel(context);
		dm = new DayBookModel(context);

		lvDayBook.setAdapter(dba);

		handler = new Handler() {
			@Override
			public void handleMessage(android.os.Message msg) {

				switch (msg.what) {
				case OperateCode.GET_FAMILY:
					if (msg.arg1 == ErrorCode.SUCCESS) {
						families = (List<Family>) msg.obj;
						Family f = new Family();// 自己作为虚拟家庭
						f.setId(Common.currentUser.getId());
						f.setName(Common.currentUser.getName());
						families.add(0, f);
						familiesName = new String[families.size()];
						for (int i = 0; i < families.size(); i++) {
							familiesName[i] = families.get(i).getName();
						}

						// 初始化记录列表
						refreshDayBook();
					} else {
						Common.showErrorInfo(DayBookPage.this.context,
								msg.arg1, "", 0);
					}
					break;
				case OperateCode.GET:// 显示流水账
					pd.cancel();
					if (msg.arg1 == ErrorCode.SUCCESS) {
						daybooks.clear();
						List<DayBook> temp = (List<DayBook>) msg.obj;
						daybooks.addAll(temp);
						dba.notifyDataSetChanged();
						// List<Map<String, Object>> daybookMaps = new
						// ArrayList<Map<String, Object>>();
						// for (DayBook item : daybooks) {
						// Map<String, Object> map = new HashMap<String,
						// Object>();
						// map.put("money", item.getMoney());
						// map.put("type", item.getCategory().getName());
						// map.put("payer", item.getPayer().getName());
						//
						// StringBuilder sb = new StringBuilder();
						// for (int i = 0; i < item.getCustomers().size(); i++)
						// {
						// sb.append(item.getCustomers().get(i).getName());
						// sb.append(",");
						// }
						// map.put("consumer", sb.toString());
						// SimpleDateFormat sdf = new SimpleDateFormat(
						// "yyyy年MM月dd日");
						// map.put("date", sdf.format(item.getDate()));
						// map.put("remark", item.getDescription());
						// daybookMaps.add(map);
						// }
						// SimpleAdapter sa = new SimpleAdapter(
						// DayBookPage.this.context, daybookMaps,
						// R.layout.layout_daybook_list_item,
						// new String[] { "money", "type", "payer",
						// "consumer", "date", "remark" },
						// new int[] { R.id.tvMoney, R.id.tvType,
						// R.id.tvPayer, R.id.tvConsumer,
						// R.id.tvDate, R.id.tvRemark });
						// lvDayBook.setAdapter(sa);
					} else if (msg.arg1 == ErrorCode.TOKEN_OVERDUE) {
						Common.loginTimeOut(DayBookPage.this.context);
					} else {
						Common.showErrorInfo(DayBookPage.this.context,
								msg.arg1, "加载失败", 0);
					}
					break;
				default:
					break;
				}
			};
		};

		lvDayBook.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			}
		});

		initFamily();

		// 初始化记录列表
		// refreshDayBook();
	}

	private void initControl() {
		ivRefresh = (ImageView) context.findViewById(R.id.ivRefresh_D);
		ivFilter = (ImageView) context.findViewById(R.id.ivFilter_D);
		lvDayBook = (ListView) context.findViewById(R.id.lvRecord);

		ivFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Builder builder = new AlertDialog.Builder(
						DayBookPage.this.context);
				builder.setTitle("家庭");
				builder.setSingleChoiceItems(familiesName, 0,

				new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						selectedFamilyIndex = arg1;
					}
				});
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								refreshDayBook();
							}
						});
				builder.create().show();
			}
		});

		ivRefresh.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				refreshDayBook();
			}
		});
	}

	/**
	 * 初始化家庭
	 */
	private void initFamily() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				fm.getMyFamily(handler);
			}
		}).start();
	}

	/**
	 * 刷新列表
	 */
	private void refreshDayBook() {
		pd = AlertDialogHelper.showWaitProgressDialog(context, "加载中…");
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (selectedFamilyIndex == 0) {
					dm.get("0", handler);
				} else {
					dm.get(families.get(selectedFamilyIndex).getId(), handler);
				}
			}
		}).start();
	}

	public class DaybookAdapter extends BaseAdapter {

		@Override
		public int getCount() {

			return daybooks.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@SuppressLint("NewApi")
		@Override
		public View getView(int index, View cv, ViewGroup vg) {
			ViewHolder vh; 
			if (cv != null) {
				vh = (ViewHolder) cv.getTag();
			} else {
				cv = context.getLayoutInflater().inflate(
						R.layout.layout_daybook_list_item, vg, false);
				vh = new ViewHolder();
				vh.ivPicture = (ImageView) cv.findViewById(R.id.ivPicture);
				vh.tvMoney = (TextView) cv.findViewById(R.id.tvMoney);
				vh.tvType = (TextView) cv.findViewById(R.id.tvType);
				vh.tvPayer = (TextView) cv.findViewById(R.id.tvPayer);
				vh.tvConsumer = (TextView) cv.findViewById(R.id.tvConsumer);
				vh.tvRemark = (TextView) cv.findViewById(R.id.tvRemark);
				vh.tvAddress = (TextView) cv.findViewById(R.id.tvAddress);
				vh.tvDate = (TextView) cv.findViewById(R.id.tvDate);
				cv.setTag(vh);
			}
			DayBook dbook = daybooks.get(index);
			vh.tvMoney.setText(String.valueOf(dbook.getMoney()));
			vh.tvType.setText(dbook.getCategory().getName());
			vh.tvPayer.setText(dbook.getPayer().getName());
			StringBuilder sb = new StringBuilder();
			List<Host> customers = dbook.getCustomers();
			for (int i = 0; i < customers.size(); i++) {
				sb.append(customers.get(i).getName());
				if (i < customers.size() - 1)
					sb.append(";");
			}
			vh.tvConsumer.setText(sb.toString());
			if (dbook.getDescription().equals(""))

				vh.tvRemark.setText("无备注");
			else
				vh.tvRemark.setText(dbook.getDescription());
			vh.tvAddress.setText(dbook.getLocation().getAddress());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
			vh.tvDate.setText(sdf.format(dbook.getDate()));
			// 异步下载图片
			List<String> temp = dbook.getPictures();
			if (temp != null && temp.size() > 0) {
				ImageView iv = vh.ivPicture;
				String url = dbook.getPictures().get(0);
				iv.setTag(url);

				if (cachImg.containsKey(url)) {
					anim = AnimationUtils.loadAnimation(context,
							R.animator.picture_anim);
					iv.startAnimation(anim);
					iv.setImageBitmap(cachImg.get(url));
				} else {
					iv.setImageBitmap(null);
					DownLoadTask dlt = new DownLoadTask(iv);
					dlt.execute(url);
				}
			}
			return cv;
		}
	}

	public class ViewHolder {
		public ImageView ivPicture;
		public TextView tvMoney;
		public TextView tvType;
		public TextView tvPayer;
		public TextView tvConsumer;
		public TextView tvRemark;
		public TextView tvAddress;
		public TextView tvDate;
	}

	public class DownLoadTask extends AsyncTask<String, Void, Bitmap> {

		private ImageView ivShow;
		private String urlString;

		public DownLoadTask(ImageView iv) {
			ivShow = iv;
		}

		@Override
		protected Bitmap doInBackground(String... arg0) {
			urlString = arg0[0];

			if (!ivShow.getTag().toString().equals(urlString)) {
				return null;
			} else {
				return HttpHelper.getPicture("DayBookPicture/" + urlString);
			}
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if (result == null)
				return;
			else {
				if (cachImg.size() > 50) {
					// Iterator<String> i = cachImg.keySet().iterator();
					// int count = 0;
					// while (i.hasNext()) {
					// cachImg.remove(i.next());
					// count++;
					// if (count > 5)
					// break;
					// }
					cachImg.clear();
				}
				if (!cachImg.containsKey(urlString)) {
					cachImg.put(urlString, result);
				}
				if (ivShow.getTag().toString().equals(urlString)) {
					anim = AnimationUtils.loadAnimation(context,
							R.animator.picture_anim);
					ivShow.startAnimation(anim);
					ivShow.setImageBitmap(result);
					ivShow.setMinimumHeight(0);
				}
			}
		}
	}

}
